<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        class="filter-item"
        placeholder="输入关键字进行过滤"
        v-model="listQuery.keyword"
        style="width: 30%"
      >
      </el-input>
      <!--      <el-input v-model="listQuery.title" placeholder="Title" style="width: 200px;" class="filter-item"-->
      <!--                @keyup.enter.native="handleFilter"-->
      <!--      />-->
      <!--      <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">-->
      <!--        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />-->
      <!--      </el-select>-->
      <!--      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">-->
      <!--        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />-->
      <!--      </el-select>-->
      <!--      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">-->
      <!--        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />-->
      <!--      </el-select>-->
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList"
                       style="margin-left: 10px"
            >
              搜索
            </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate"
      >
        添加身份
      </el-button>
<!--      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"-->
<!--                 @click="handleDownload"-->
<!--      >-->
<!--        导出-->
<!--      </el-button>-->
      <!--      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">-->
      <!--        审核-->
      <!--      </el-checkbox>-->
    </div>
    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="ID" min-width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="180" align="center" label="身份">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>

      <el-table-column min-width="120" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>


      <el-table-column align="center" label="操作" min-width="120">
        <template slot-scope="scope">
          <el-button type="primary" size="small" icon="el-icon-edit" circle @click="handleUpdate(scope.row)">
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" circle @click="del(scope.row.id)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px"
               style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name"/>
        </el-form-item>
        <el-form-item label="筛选菜单">
          <el-input
            placeholder="输入关键字进行过滤"
            v-model="filterText"
          ></el-input>
        </el-form-item>
        <el-form-item label="选择菜单">
          <el-tree
            :data="menus"
            :checkStrictly=true
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            :props="defaultProps"
            ref="tree"
            show-checkbox
            :filter-node-method="filterNode"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <center>
          <el-button @click="resetForm">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():createData()">
            提交
          </el-button>
        </center>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, create, del ,detail ,roles_detail, submitRoles} from '@/api/role'
import { getMenus } from '@/api/menu'
import Pagination from '@/components/Pagination'
import { createMenus, delMenus } from '@/api/menu'
import store from '@/store'
import router from '@/router' // Secondary package based on el-pagination

export default {
  name: 'RolesList',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      menus: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: ''
      },
      temp: {
        id: undefined,
        name: '',
        menus: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      detail_menus:[],
      detail_roles:[],
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      rules: {
        name: [{ required: true, message: '身份不能为空', trigger: 'change' }]
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getMenus()
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getCheckedNodes() {
    //  console.log(this.$refs.tree.getCheckedNodes())
    },
    setCheckedNodes(row) {
      this.$refs.tree.setCheckedNodes(row);
    },
    getMenus() {
      getMenus().then(response => {
        this.menus = response.data.data
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    resetForm(){
      this.dialogFormVisible = false
      this.$refs.tree.setCheckedKeys([]);
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.temp.menus = this.$refs.tree.getCheckedNodes();
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.temp).then(response => {
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            if (response.data.code == 200) {
              this.$notify.success({
                title: '成功',
                message: response.data.msg,
                type: 'success',
                duration: 2000
              })
              this.resetTemp()
              this.getList()
            } else {
              this.$notify.error({
                title: '失败',
                message: response.data.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.temp.id = row.id
      this.temp.name = row.name
      detail(row.id).then(response=>{
        this.setCheckedNodes(response.data.menus)
      })
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    del(id) {
      this.$confirm('确认要删除该条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(id).then(response => {
          // this.list.unshift(this.temp)
          if (response.data.code == 200) {
            this.$notify.success({
              title: '成功',
              message: response.data.msg,
              type: 'success',
              duration: 2000
            })
            this.resetTemp()
            this.getList()
            const accessRoutes = store.dispatch('permission/generateRoutes', store.getters.token)
            router.addRoutes(accessRoutes)
          } else {
            this.$notify.error({
              title: '失败',
              message: response.data.msg,
              duration: 2000
            })
          }
        })
      }).catch(() => {

      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        menus:[]
      }
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}

.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
